package com.heima.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Override
    public ResponseResult loginAuth(LoginDto dto) {

        //1. 如果请求参数都有值，则按照正常登录用户处理
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {

            //1.1 判断用户是否存在 select * from ap_user where phone=?

//            LambdaQueryWrapper<ApUser> lambdaQueryWrapper = new LambdaQueryWrapper();
//            lambdaQueryWrapper.eq(ApUser::getPhone,dto.getPhone());
//            ApUser apUser = this.getOne(lambdaQueryWrapper);

//            ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));

            ApUser apUser = this.lambdaQuery().eq(ApUser::getPhone, dto.getPhone()).one();
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }

            //1.2 判断密码是否正确
            String loginPwd = dto.getPassword(); //登录的明文密码
            String dbPwd = apUser.getPassword();//表中的密文密码
            boolean result = BCrypt.checkpw(loginPwd, dbPwd);
            if(!result){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //1.3 判断状态是否正常
            if(apUser.getStatus()!=0){
                return ResponseResult.errorResult(AppHttpCodeEnum.INVALID_USER);
            }

            //1.4 为登录成功用户生成Token
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            apUser.setPassword("");

            //1.5 封装响应数据并响应
            Map resultMap = new HashedMap();
            resultMap.put("user",apUser);
            resultMap.put("token",token);
            return ResponseResult.okResult(resultMap);
        } else {
            //2. 如果请求参数都无值，则按照游客访问处理

            //2.1 所有的游客都统一的根据0做为ID生成Token
            String token = AppJwtUtil.getToken(0L);

            //2.2 封装响应数据并响应
            Map resultMap = new HashedMap();
            resultMap.put("token", token);
            return ResponseResult.okResult(resultMap);
        }
    }
}
